package com.qs.cwams.controller;


import com.qs.common.framework.util.RedisUtils;
import com.qs.cwams.service.ApiService;
import com.qs.cwams.util.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 中控门禁通信接口
 * @author huwei
 */
@RestController
@RequestMapping("/iclock")
public class ApiController {
    private static final Logger logger = LoggerFactory.getLogger(ApiController.class);

    @Autowired
    private ApiService apiService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 指纹机初始化
     * @param SN
     * @param options
     * @param language
     * @param pushver
     * @return
     */
    @GetMapping(value="/cdata")
    public String init(String SN, String options, String language, String pushver){
        logger.info(String.format("指纹机初始化 序列号: %s 配置参数: %s 语言: %s push协议版本: %s", SN, options, language, pushver));
        return apiService.init(SN);
    }

    /**
     * 正常时此接口保持心跳
     * @param SN
     */
    @RequestMapping(value = "/getrequest", produces = "text/plain;charset=GB2312")
    public String getRequest(String SN, HttpServletRequest req){
        apiService.heart(SN, IpUtil.getIpAddress(req));
        return "OK";
    }

    /**
     * 大数据处理时此接口保持心跳
     * @param SN
     * @return
     */
    @RequestMapping("/ping")
    public String ping(String SN, HttpServletRequest req){
        apiService.heart(SN, IpUtil.getIpAddress(req));
        return "OK";
    }

    /**
     * 上传考勤记录
     * @param data
     * @param SN
     * @param table
     * @param Stamp
     * @return
     */
    @RequestMapping(value = "/cdata",method = RequestMethod.POST)
    public String handle(@RequestBody String data, String SN, String table, String Stamp){
        logger.info(String.format("序列号 %s 上传类型为 %s , 时间戳为: %s", SN, table, Stamp));
        logger.info("设备上传的实时记录为 \n" + data);
        if ("ATTLOG".equals(table)) {
            int size = apiService.attLogHandle(data, SN, table);
            return "OK:" + size;
        } else {
            return "OK";
        }
    }

    /**
     * 指纹机执行命令结果
     * @param result
     * @param SN
     * @return
     */
    @PostMapping(value="/devicecmd")
    public String deviceCmd(@RequestBody String result, String SN){
        apiService.callback(result, SN);
        return "OK";
    }
}

